這邊改成只要在聊天室輸入關鍵字就會傳出LINE emoji訊息
前面處理LINE emoji訊息的函式中增加lastLength參數,用來考慮訊息不是從第一個字抓取的情況
def handle_emoji_text(text,emojis,lastLength):
if(not emojis is None):
for emoji in emojis:
index =emoji.index-lastLength
text="%s%s%s"%(text[:index],'$',text[index+emoji.length:])
lastLength = lastLength + emoji.length-1
return text
def handle_emoji(emojis,lastLength):
if(not emojis is None):
for emoji in emojis:
emoji.index =emoji.index-lastLength
lastLength = lastLength + emoji.length-1
return emojis
收到message event時先把關鍵字存至list
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
cursor = conn.cursor()
cursor.execute(f"SELECT keyword FROM group_buying_message;")
rows = cursor.fetchall()
cursor.close()
keywords=[]
for row in rows:
keywords.append("".join(row))
前面改為輸入訊息是否為關鍵字,從後面動作沒動
if(event.message.text in keywords):
key=event.message.text
cursor=conn.cursor()
#將取得的key作為關鍵字在group_buying_message裡找到訊息文字
cursor.execute(f"SELECT message_text FROM group_buying_message WHERE keyword='{key}';")
message_text = cursor.fetchone()
#找到訊息文字後面才執行
if(not message_text is None):
#用key在group_buying_message裡找到訊息文字的mid,再用mid從message_emoji裡找到LINE emoji資訊
cursor.execute(f"SELECT index,product_id,emoji_id FROM message_emoji WHERE mid=(SELECT mid FROM group_buying_message WHERE keyword='{key}');")
rows = cursor.fetchall()
cursor.close()
emojis=[]
#將資料一筆一筆寫入list中
for row in rows:
emojis.append({'index': row[0],'productId': row[1],'emojiId': row[2]})
#message_text資料型態為元組,不能直接丟入TextSendMessage(),用join重組成字串
message=TextSendMessage("".join(message_text),emojis)
在新增訊息的函式中增加關鍵字參數add 關鍵字 訊息
lastLength用來定位訊息位置
if(event.message.text[:3:]=="add"):
lastLength=event.message.text.find(" ",4)
handled_text=handle_emoji_text(event.message.text[lastLength+1::],event.message.emojis,lastLength+1)
handled_emoji=handle_emoji(event.message.emojis,lastLength+1)
insert_emoji_message(handled_text,event.message.text[4:lastLength:],handled_emoji)
message=TextSendMessage(handled_text,handled_emoji)